package com.scuec.trainingmanagementsys.controller;

import com.scuec.trainingmanagementsys.entity.WeeklyReport;
import com.scuec.trainingmanagementsys.service.TeamMemberService;
import com.scuec.trainingmanagementsys.service.WeeklyReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/weeklyReport")
@CrossOrigin
public class WeeklyReportController {
    @Autowired
    private WeeklyReportService weeklyReportService;
    @Autowired
    private TeamMemberService teamMemberService;

    // 重构后的获取当前学生ID的方法
    private Integer getCurrentStudentId(HttpServletRequest request) {
        String studentIdStr = request.getParameter("studentID");
        if (studentIdStr == null || studentIdStr.isEmpty()) {
            // 可以根据实际情况进行处理，这里简单返回 null
            return null;
        }
        return Integer.parseInt(studentIdStr);
    }

    // 添加周报（仅Leader可操作）
    @PostMapping("/add")
    public Map<String, Object> addWeeklyReport(@RequestBody WeeklyReport weeklyReport) {
        Integer studentID = weeklyReport.getStudentID();
        System.out.println("Received studentID: " + studentID);
        return weeklyReportService.addWeeklyReport(weeklyReport, studentID);
    }

    // 删除周报（仅发布者可操作）
    @DeleteMapping("/delete/{weeklyReportID}")
    public Map<String, Object> deleteWeeklyReport(@PathVariable Integer weeklyReportID, @RequestParam Integer studentID) {
        return weeklyReportService.deleteWeeklyReport(weeklyReportID, studentID);
    }

    // 更新周报
    @PutMapping("/update")
    public Map<String, Object> updateWeeklyReport(@RequestBody WeeklyReport weeklyReport) {
        return weeklyReportService.updateWeeklyReport(weeklyReport);
    }

    // 根据ID查询周报
    @GetMapping("/get/{weeklyReportID}")
    public WeeklyReport getWeeklyReport(@PathVariable Integer weeklyReportID) {
        return weeklyReportService.getWeeklyReportById(weeklyReportID);
    }

    // 查询团队所有周报（团队成员均可查看）
    @GetMapping("/list/team/{teamID}")
    public Map<String, Object> getWeeklyReportsByTeam(@PathVariable Integer teamID) {
        Map<String, Object> result = new HashMap<>();
        List<WeeklyReport> reports = weeklyReportService.getWeeklyReportsByTeamId(teamID);
        result.put("code", 200);
        result.put("data", reports);
        result.put("message", "查询成功");
        return result;
    }

    // 查询当前用户提交的周报
    @GetMapping("/list/my")
    public Map<String, Object> getMyWeeklyReports(@RequestParam Integer studentID) {
        Map<String, Object> result = new HashMap<>();
        List<WeeklyReport> reports = weeklyReportService.getWeeklyReportsByStudentId(studentID);
        result.put("code", 200);
        result.put("data", reports);
        result.put("message", "查询成功");
        return result;
    }

    // 查询学生提交的周报
    @GetMapping("/list/student/{studentID}")
    public Map<String, Object> getWeeklyReportsByStudent(@PathVariable Integer studentID) {
        Map<String, Object> result = new HashMap<>();
        List<WeeklyReport> reports = weeklyReportService.getWeeklyReportsByStudentId(studentID);
        result.put("code", 200);
        result.put("data", reports);
        result.put("message", "查询成功");
        return result;
    }

    // 查询当前学生的周报信息，关联查询student、project和team表
    @GetMapping("/wrlist/student/with-relations/{studentID}")
    public Map<String, Object> getWeeklyReportsByStudentWithRelations(@PathVariable Integer studentID) {
        Map<String, Object> result = new HashMap<>();
        List<WeeklyReport> reports = weeklyReportService.getWeeklyReportsByStudentIdWithRelations(studentID);
        result.put("code", 200);
        result.put("data", reports);
        result.put("message", "查询成功");
        return result;
    }

    // 检查用户是否为团队 Leader
    @GetMapping("/isTeamLeader/{teamID}")
    public boolean isTeamLeader(@PathVariable Integer teamID, @RequestParam Integer studentID) {
        return weeklyReportService.isTeamLeader(teamID, studentID);
    }

    // 添加新接口：根据学生ID获取其所在团队的周报
    @GetMapping("/list/team/byStudent")
    public Map<String, Object> getWeeklyReportsByStudentTeam(@RequestParam Integer studentId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 根据学生ID获取TeamMemberID
            Integer teamMemberId = teamMemberService.getTeamMemberIdByStudentId(studentId);
            if (teamMemberId == null) {
                result.put("code", 404);
                result.put("message", "未找到该学生的团队成员信息");
                return result;
            }

            // 根据TeamMemberID获取TeamID
            Integer teamId = teamMemberService.getTeamIdByTeamMemberId(teamMemberId);
            if (teamId == null) {
                result.put("code", 404);
                result.put("message", "未找到该团队成员所属的团队");
                return result;
            }

            // 根据TeamID获取团队周报
            List<WeeklyReport> reports = weeklyReportService.getWeeklyReportsByTeamId(teamId);
            result.put("code", 200);
            result.put("data", reports);
            result.put("message", "查询成功");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "服务器错误: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("/list/withProjectName")
    public Map<String, Object> getWeeklyReportsWithProjectName() {
        Map<String, Object> result = new HashMap<>();
        List<WeeklyReport> reports = weeklyReportService.getWeeklyReportsWithProjectName();
        result.put("code", 200);
        result.put("data", reports);
        result.put("message", "查询成功");
        return result;
    }

    @GetMapping("/wrlist/team/with-relations/{teamID}")
    public Map<String, Object> getWeeklyReportsByTeamWithRelations(@PathVariable Integer teamID) {
        Map<String, Object> result = new HashMap<>();
        List<WeeklyReport> reports = weeklyReportService.getWeeklyReportsByTeamIdWithRelations(teamID);
        result.put("code", 200);
        result.put("data", reports);
        result.put("message", "查询成功");
        return result;
    }

    // 新增根据学生ID获取团队周报的接口
    @GetMapping("/wrlist/student/team/with-relations/{studentID}")
    public Map<String, Object> getWeeklyReportsByStudentTeamWithRelations(@PathVariable Integer studentID) {
        Map<String, Object> result = new HashMap<>();
        // 根据学生ID获取所在团队ID
        Integer teamID = teamMemberService.getTeamIdByStudentId(studentID);
        if (teamID == null) {
            result.put("code", 404);
            result.put("message", "未找到该学生所属团队");
            return result;
        }
        // 根据团队ID获取所有周报
        List<WeeklyReport> reports = weeklyReportService.getWeeklyReportsByTeamIdWithRelations(teamID);
        result.put("code", 200);
        result.put("data", reports);
        result.put("message", "查询成功");
        return result;
    }

    // 获取所有周报信息
    @GetMapping("/list/all")
    public Map<String, Object> getAllWeeklyReports() {
        Map<String, Object> result = new HashMap<>();
        List<WeeklyReport> reports = weeklyReportService.getAllWeeklyReports();
        result.put("code", 200);
        result.put("data", reports);
        result.put("message", "查询成功");
        return result;
    }

    // 根据项目ID获取周报信息
    @GetMapping("/list/team/byProject")
    public Map<String, Object> getWeeklyReportsByProjectId(@RequestParam Integer projectId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<WeeklyReport> reports = weeklyReportService.getWeeklyReportsByProjectId(projectId);
            result.put("code", 200);
            result.put("data", reports);
            result.put("message", "查询成功");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询失败: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("/count/last7days")
    public Map<String, Object> getWeeklyReportCountLast7Days() {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> counts = weeklyReportService.getWeeklyCountLast7Days();
        result.put("code", 200);
        result.put("data", counts);
        result.put("message", "查询成功");
        return result;
    }
}